package com.example.yichuangyun.ui.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ItemCallRecordBinding;
import com.example.yichuangyun.databinding.ItemCallRecordContentBinding;
import com.example.yichuangyun.databinding.LayoutEmptyList2Binding;
import com.example.yichuangyun.databinding.LayoutEmptyListBinding;
import com.example.yichuangyun.dialog.PlayRecordDialog;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.CallRecordDataModel;
import com.example.yichuangyun.mvvm.ui.activity.CallRecordActivity;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DateUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ScreenUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UiUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 通话记录适配器
 */
public class CallRecordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /**
     * viewType--分别为item以及空view
     */
    private final int VIEW_TYPE_ITEM = 1;
    private static final int VIEW_TYPE_EMPTY = 0;
    private final Context context;
    private List<CallRecordDataModel.CallListModel> mData;
    /**
     * 0列表、1详情列表
     */
    private int flag;
    private OnCallListener onCallListener;
    /**
     * 录音权限
     */
    private List<String> soundRecordingJobNumbers = new ArrayList<>();

    public CallRecordAdapter(Context context, List<CallRecordDataModel.CallListModel> mData) {
        this.context = context;
        this.mData = mData;
    }

    public CallRecordAdapter(Context context, List<CallRecordDataModel.CallListModel> mData, int flag) {
        this.context = context;
        this.mData = mData;
        this.flag = flag;
    }

    public void onRefresh(List<CallRecordDataModel.CallListModel> mList) {
        if (mList != null) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.clear();
            this.mData.addAll(mList);
            notifyDataSetChanged();
            if (!mData.isEmpty() && mData.get(0) != null) {
                if (mData.get(0).getList() != null && !mData.get(0).getList().isEmpty()) {
                    soundRecordingJobNumbers = mData.get(0).getList().get(0).getSoundRecordingJobNumbers();
                }
            }
        }
    }

    public void addData(List<CallRecordDataModel.CallListModel> mList) {
        if (mList != null && mList.size() != 0) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //在这里根据不同的viewType进行引入不同的布局
        if (viewType == VIEW_TYPE_EMPTY) {
            LayoutEmptyList2Binding emptyListBinding = LayoutEmptyList2Binding.inflate(LayoutInflater.from(context), parent, false);
            return new EmptyViewHolder(emptyListBinding);
        } else {
            ItemCallRecordBinding itemCallRecordBinding = ItemCallRecordBinding.inflate(LayoutInflater.from(context), parent, false);
            return new MyViewHolder(itemCallRecordBinding);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyViewHolder) {
            CallRecordDataModel.CallListModel model = mData.get(position);
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            myViewHolder.binding.recyclerView.setAdapter(new MyCallAdapter(mData.get(position).getList()));
            if (flag == 1) {
                LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) myViewHolder.binding.tvTopTime.getLayoutParams();
                linearParams.topMargin = 0;
                linearParams.height = ScreenUtil.dip2px(25);
                myViewHolder.binding.tvTopTime.setLayoutParams(linearParams);
                if (position == 0) {
                    myViewHolder.binding.itemView.setPadding(0, ScreenUtil.dip2px(15), 0, 0);
                }
            }
//            myViewHolder.binding.tvTopTime.setText(DateUtil.getDate(model.getTrackDate()));
            myViewHolder.binding.tvTopTime.setText(CommonUtil.checkText(model.getTrackDate()));
            if (position == 0) {
                myViewHolder.binding.tvTopTime.setVisibility(View.VISIBLE);
            }
            if (position > 0) {
                String date1 = model.getTrackDate();
                String date2 = mData.get(position - 1).getTrackDate();
                if (!TextUtils.isEmpty(date1) && !TextUtils.isEmpty(date2)) {
                    myViewHolder.binding.tvTopTime.setVisibility(date1.equals(date2) ? View.GONE : View.VISIBLE);
                }
            }
        } else if (holder instanceof EmptyViewHolder) {
            EmptyViewHolder emptyHolder = (EmptyViewHolder) holder;
            emptyHolder.binding.text.setText(context.getString(R.string.no_call_record));
        }
    }

    class MyCallAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final List<CallRecordDataModel.CallListModel.CallRecordModel> mData;

        public MyCallAdapter(List<CallRecordDataModel.CallListModel.CallRecordModel> mData) {
            this.mData = mData;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemCallRecordContentBinding itemCallRecordContentBinding = ItemCallRecordContentBinding.inflate(LayoutInflater.from(context), parent, false);
            return new CallViewHolder(itemCallRecordContentBinding);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof CallViewHolder) {
                CallViewHolder myViewHolder = (CallViewHolder) holder;
                CallRecordDataModel.CallListModel.CallRecordModel model = mData.get(position);
                // 1 管帮手、2 电话系统、3 AI外呼、4 回拨外呼
                switch (model.getTelType()) {
                    case 1:
                        myViewHolder.binding.tvLabel.setText(context.getString(R.string.app_name));
                        break;
                    case 2:
                        myViewHolder.binding.tvLabel.setText(context.getString(R.string.call_system));
                        break;
                    case 3:
                        myViewHolder.binding.tvLabel.setText(context.getString(R.string.ai));
                        break;
                    case 10:
                        myViewHolder.binding.tvLabel.setText(context.getString(R.string.callback_outbound));
                        break;
                    default:
                        myViewHolder.binding.tvLabel.setText(context.getString(R.string.other));
                        break;
                }

                if (flag == 1) {
                    //有权限才能听录音
                    if (soundRecordingJobNumbers != null && !soundRecordingJobNumbers.contains(model.getZuoxi())) {
                        myViewHolder.binding.ivPlay.setVisibility(View.GONE);
                    } else {
                        String checkField = (model.getTelType() == 2 || model.getTelType() == 3) ? model.getRecfilepath() : model.getLinkedid();
                        myViewHolder.binding.ivPlay.setVisibility(TextUtils.isEmpty(checkField) || model.getCallSec() == 0 ? View.GONE : View.VISIBLE);
                    }
                } else {
                    String checkField = (model.getTelType() == 2 || model.getTelType() == 3) ? model.getRecfilepath() : model.getLinkedid();
                    myViewHolder.binding.ivPlay.setVisibility(TextUtils.isEmpty(checkField) || model.getCallSec() == 0 ? View.GONE : View.VISIBLE);
                }

                String telNumber = flag == 0 ? model.getTelNumber() : TextUtils.isEmpty(model.getTelNumberEn()) ? model.getTelNumber() : model.getTelNumberEn();
                myViewHolder.binding.tvName.setText(TextUtils.isEmpty(model.getUserName()) ? telNumber : model.getUserName() + " · " + telNumber);
                myViewHolder.binding.tvName.setTextColor(ContextCompat.getColor(context, model.getCallType() == 3 ? R.color.color_E55C5C : R.color.color_3B3A40)); // 未接红色字体
                if (model.getLabelType() != null) {
                    myViewHolder.binding.llBlack.setVisibility(View.VISIBLE);
                    myViewHolder.binding.tvBlack.setText(UiUtils.getSelectLabelType(model.getLabelType()));
                } else {
                    myViewHolder.binding.llBlack.setVisibility(View.GONE);
                }
                myViewHolder.binding.tvCallType.setText(UiUtils.getCallType(model.getCallType()));
                myViewHolder.binding.tvCallTime.setText(!TextUtils.isEmpty(model.getTrackTime()) ? model.getTrackTime().substring(11) : "-");

                myViewHolder.binding.ivCall.setVisibility(model.getCallType() == 2 ? View.VISIBLE : View.INVISIBLE);
                // 通话时长
                if (model.getCallSec() > 0) {
                    myViewHolder.binding.llCallLength.setVisibility(View.VISIBLE);
                    myViewHolder.binding.tvCallLength.setText(DateUtil.getTimeBySecond3(model.getCallSec()));
                } else {
                    myViewHolder.binding.llCallLength.setVisibility(View.GONE);
                }

                myViewHolder.binding.ivPlay.setOnClickListener(v -> {
                    if (CommonUtil.isCanClick()) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constant.modelKey, model);
                        JumpIntent.jump((Activity) context, CallRecordActivity.class, bundle);
                    }
                });

                myViewHolder.itemView.setOnClickListener(v -> {
                    if (CommonUtil.isCanClick()) {
                        if (onCallListener != null) {
                            onCallListener.callListener(model.getTelNumber());
                        }
                    }
                });

                myViewHolder.itemView.setOnLongClickListener(v -> {
                    ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData mClipData = ClipData.newPlainText("Label", model.getTelNumber());
                    cm.setPrimaryClip(mClipData);
                    ToastHelper.show(context.getString(R.string.copy_contact_num));
                    return true;
                });
            }
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }

    @Override
    public int getItemCount() {
        //同时这里也需要添加判断，如果mData.size()为0的话，只引入一个布局，就是emptyView
        // 那么，这个recyclerView的itemCount为1
        if (mData.size() == 0) {
            return 1;
        }
        //如果不为0，按正常的流程跑
        return mData.size();
    }

    @Override
    public int getItemViewType(int position) {
        //在这里进行判断，如果我们的集合的长度为0时，我们就使用emptyView的布局
        if (mData.size() == 0) {
            return VIEW_TYPE_EMPTY;
        }
        //如果有数据，则使用ITEM的布局
        return VIEW_TYPE_ITEM;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        ItemCallRecordBinding binding;

        public MyViewHolder(ItemCallRecordBinding itemCallRecordBinding) {
            super(itemCallRecordBinding.getRoot());
            binding = itemCallRecordBinding;
        }
    }

    static class EmptyViewHolder extends RecyclerView.ViewHolder {

        LayoutEmptyList2Binding binding;

        public EmptyViewHolder(LayoutEmptyList2Binding emptyListBinding) {
            super(emptyListBinding.getRoot());
            binding = emptyListBinding;
        }
    }

    static class CallViewHolder extends RecyclerView.ViewHolder {

        ItemCallRecordContentBinding binding;

        public CallViewHolder(ItemCallRecordContentBinding itemCallRecordContentBinding) {
            super(itemCallRecordContentBinding.getRoot());
            binding = itemCallRecordContentBinding;
        }
    }

    public interface OnCallListener {
        void callListener(String number);
    }

    public void setOnCallListener(OnCallListener onCallListener) {
        this.onCallListener = onCallListener;
    }
}
